<script setup lang="ts">
import { computed, ref, inject, provide } from 'vue'
import { type Component } from "@/models/component";
import { getComponent } from "@/core/componentMapper";
import Error from "./Error.vue";
import * as injectKeys from "@/services/injectKeys";
import { TForeachRow } from '@/models/types';


const utilsServices = inject(injectKeys.utilsKey)!


const props = defineProps<{ component: Component, foreachRow?: TForeachRow }>()
const model = props.component

if (props.foreachRow) {
    provide('foreachRow', props.foreachRow)
}

const cp = getComponent(props.component.tag)

// TODO:
const visible = computed(() => {
    if (model.visible === undefined) {
        return true
    }

    if (typeof model.visible !== 'boolean') {
        const sqlInfo = model.visible

        const sqlQuery = utilsServices.createSqlQuery(model.id, sqlInfo.sql)
        const data = sqlQuery.query()

        if (data.rows.length === 0) {
            return false
        }

        const firstValue = data.rows[0][data.fields[0]]
        return firstValue
    }

    return model.visible as boolean

})

let styles = model.styles

if (model.gridArea) {
    styles = {
        ...styles,
        gridArea: model.gridArea
    }
}

</script>

<template>
    <Error v-if="visible">
        <component :style="styles" :id="props.component.id" :class="model.classes" :data-cp-tag="props.component.tag"
            :data-debug-tag="props.component.debugTag" :is="cp" :model="props.component">
        </component>

    </Error>
</template>

<style scoped></style>